package com.my.schedule.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.my.common.constans.ScheduleConstants;
import com.my.common.redis.CacheService;
import com.my.model.schedule.dtos.Task;
import com.my.model.schedule.pojos.Taskinfo;
import com.my.model.schedule.pojos.TaskinfoLogs;
import com.my.schedule.mapper.TaskInfoLogsMapper;
import com.my.schedule.mapper.TaskInfoMapper;
import com.my.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@Transactional
public class TaskServiceImpl implements TaskService {
    /**
     * 添加延迟任务
     * @param task  任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1.将任务添加到数据库中
        boolean success = addTaskToDb(task);

        if(success) {
            //2.将任务添加到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private TaskInfoLogsMapper taskInfoLogsMapper;
    /**
     * 将任务添加到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;

        try {
            //1.保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskInfoMapper.insert(taskinfo);

            //2.设置任务id
            task.setTaskId(taskinfo.getTaskId());

            //3.保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskInfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    @Autowired
    private CacheService cacheService;
    /**
     * 将任务添加到redis
     * @param task
     */
    private void addTaskToCache(Task task) {
        //1.构造key
        String key = task.getTaskType()+"_"+task.getPriority();

        //2.获取5分钟之后的时间 毫秒级
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextScheduleTime = calendar.getTimeInMillis();

        //3.如果任务执行时间小于等于当前时间，存入list
        if(task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if(task.getExecuteTime() <= nextScheduleTime) {
            //4.如果任务执行时间在5分钟之内，存入zSet
            cacheService.zAdd(ScheduleConstants.FUTURE + key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    /**
     * 删除任务
     * @param taskId      任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //1.删除任务并更新日志
        Task task = UpdateDb(taskId,ScheduleConstants.EXECUTED);

        //2.从Redis中删除任务
        if(task != null) {
            removeFromCache(task);
            log.info("删除Redis中的任务成功:{}",taskId);
            flag = true;
        }

        return flag;
    }

    /**
     * 从redis中删除任务
     * @param task
     */
    private void removeFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        if(task.getExecuteTime() <= System.currentTimeMillis()) {
            log.info("删除正要执行的任务...");
            cacheService.lRemove(ScheduleConstants.TOPIC + key,0,JSON.toJSONString(task));
        } else {
            log.info("删除将要执行的任务...");
            cacheService.zRemove(ScheduleConstants.FUTURE + key,JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新日志
     * @param taskId
     * @param status
     * @return
     */
    public Task UpdateDb(long taskId, int status) {
        Task task = null;
        try {
            //1.删除任务
            log.info("删除数据库中的任务...");
            taskInfoMapper.deleteById(taskId);

            //2.更新日志
            log.info("更新任务日志...");
            TaskinfoLogs taskinfoLogs = taskInfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskInfoLogsMapper.updateById(taskinfoLogs);

            //3.设置返回值
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }

        return task;
    }

    /**
     * 消费任务
     * @param type  任务类型
     * @param priority 任务优先级
     * @return  Task
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;

            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)) {
                task = JSON.parseObject(task_json,Task.class);
                //更新数据库   (抛弃该策略)
                // UpdateDb(task.getTaskId(),ScheduleConstants.EXECUTED);

                //接口幂等性
                TaskinfoLogs taskinfoLogs = taskInfoLogsMapper.selectById(task.getTaskId());
                //获取任务状态
                if(taskinfoLogs != null) {
                    Integer status = taskinfoLogs.getStatus();
                    if(ScheduleConstants.EXECUTED == status) {
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }
        return task;
    }

    /**
     * 定时器任务，每分钟扫描redis一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);//加锁，30秒过期
        if(StringUtils.isNotBlank(token)) {
            log.info("开始执行定时扫描redis任务...");

            //获取所有未来数据集合的key值
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                //截取后半部分 future_200_100 --> _200_100
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要清理的任务数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey,0,System.currentTimeMillis());
                if(!tasks.isEmpty()) {
                    //将这些数据添加到消费队列中
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    log.info("成功将{}下的当前需要执行的任务添加到{}",futureKey,topicKey);
                }
            }
        }
    }

    /**
     * 数据库同步任务，每五分钟执行一次
     */
    @PostConstruct  //表示服务一启动便执行一次
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        log.info("开始同步数据库任务到redis...");
        //1.清理缓存任务，避免重复
        clearCache();

        //2.获取5分钟之后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        //3.查看未来所有小于5分钟的任务
        List<Taskinfo> tasks = taskInfoMapper.selectList
                (Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if(tasks != null && tasks.size() > 0) {
            for (Taskinfo taskinfo : tasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    /**
     * 清理缓存任务
     */
    private void clearCache() {
        log.info("开始清理缓存任务...");
        //获取任务集
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }
}
